package org.vaadin.nf4v.ext.config.handler;

import org.vaadin.nf4v.core.config.AbstractConfig;
import org.vaadin.nf4v.core.config.ContextConfig;
import org.vaadin.nf4v.core.config.ContextConfigurationException;
import org.vaadin.nf4v.core.config.PageConfig;
import org.vaadin.nf4v.core.config.process.NavigationConfigProcessor;
import org.vaadin.nf4v.core.config.process.parser.ContextConfigParser;
import org.vaadin.nf4v.core.config.process.parser.PageConfigParser;
import org.vaadin.nf4v.ext.config.util.AnnotationUtil;

/**
 * Configuration extension:
 * Scans window and page classes for @OverrideHandler annotation and overrides default handler configuration.
 */
public class OverrideHandlerAnnotationParser implements ContextConfigParser, PageConfigParser {

    @Override
    public void parse(NavigationConfigProcessor navigationConfigProcessor, ContextConfig contextConfig, PageConfig pageConfig)
            throws ContextConfigurationException {
        register(navigationConfigProcessor, pageConfig, pageConfig.getPageClass());
    }

    @Override
    public void parse(NavigationConfigProcessor navigationConfigProcessor, ContextConfig contextConfig)
            throws ContextConfigurationException {
        register(navigationConfigProcessor, contextConfig, contextConfig.getWindowClass());
    }

    protected void register(NavigationConfigProcessor processor, AbstractConfig config, Class clazz)
            throws ContextConfigurationException {
        OverrideHandler ann = AnnotationUtil.getClassAnnotation(OverrideHandler.class, clazz);
        if (ann != null) {
            if (ann.handler() == null) {
                throw new ContextConfigurationException("Handler implementation class not specified in @OverrideHandler annotation " +
                        "of class " + clazz);
            }
            processor.registerHandler(config, ann.handler());
        }
    }
}
